<template>
    <div class="box">

        <!--路径-->
        <div class="box-path">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/demo/index' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>权限管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <!--表单按钮-->
        <div class="box-button">
            <el-row>
                <el-col :span="14" class="box-button-opt">
                    <el-button size="mini" type="primary" @click="dialogEditInfo(null)">添加<i
                            class="el-icon-plus el-icon--right"></i></el-button>
                    <el-button size="mini" type="danger" @click="eventDelete(null)">删除<i
                            class="el-icon-delete el-icon--right"></i></el-button>
                    <el-button size="mini" type="info">禁用<i class="el-icon-remove el-icon--right"></i></el-button>
                    <el-button size="mini" type="success">启用<i class="el-icon-success el-icon--right"></i></el-button>
                    <el-button size="mini" type="warning">导入<i class="el-icon-upload el-icon--right"></i></el-button>
                    <el-button size="mini" type="warning">导出<i class="el-icon-download el-icon--right"></i></el-button>
                </el-col>
                <el-col :span="10" class="box-button-txt">
                    <el-input placeholder="请输入内容" v-model="input3" class="input-with-select" size="mini">
                        <el-select v-model="select" slot="prepend" placeholder="请选择" size="mini">
                            <el-option label="登录账号" value="1"></el-option>
                            <el-option label="员工工号" value="2"></el-option>
                        </el-select>
                        <el-button type="success" slot="append" icon="el-icon-search">查询</el-button>
                    </el-input>
                </el-col>
            </el-row>
        </div>

        <!--数据-->
        <div class="box-data">
            <el-table ref="multipleTable" :data="dataList" tooltip-effect="dark" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55">
                </el-table-column>

                <el-table-column prop="loginName" label="登录名称">
                </el-table-column>
                <el-table-column prop="nickName" label="昵称" width="120">
                </el-table-column>
                <el-table-column label="所属角色" width="220">
                    <template slot-scope="scope">
                        <span style="margin-right:20px" v-for="(item, index) in scope.row.roleItems" :key="index">{{
                            item
                        }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                    <template slot-scope="scope">
                        <!-- if(scope.row.statue==0)  正常
                        else  禁用 -->
                        <template v-if="scope.row.statue == '0'">
                            <el-tag type="success" size="mini">正常</el-tag>
                        </template>
                        <template v-else>
                            <el-tag type="danger" size="mini">已禁用</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="createdTime" label="创建日期" width="200">
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                        <div class="buttons-opt">
                            <i type="danger" class="el-icon-edit" title="编辑" @click="dialogEditInfo(scope.row)"></i>
                            <i class="el-icon-delete" title="删除" @click="eventDelete(scope.row)"></i>
                            <i type="danger" class="el-icon-user-solid" title="配置角色"
                                @click="dialogConfigRole(scope.row.id)"></i>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!--分页-->
        <div class="box-pages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pages.pageIndex" :page-sizes="[8, 15, 20, 25]" :page-size="pages.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pages.total">
            </el-pagination>
        </div>

        <!-- Dialog -->
        <el-dialog title="配置用户角色" :visible.sync="dialogConfigVisible" width="60%">
            <div>
                <el-checkbox-group v-model="checkRoleList">
                    <el-checkbox v-for="(item, index) in roleData" :key="index" :label="item.id">{{
                        item.name
                    }}</el-checkbox>
                    <!-- <el-checkbox label="角色2"></el-checkbox>
                    <el-checkbox label="角色3"></el-checkbox>
                    <el-checkbox label="角色4"></el-checkbox> -->
                </el-checkbox-group>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogConfigVisible = false">取 消</el-button>
                <el-button type="primary" @click="eventConfigRoleSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <!--选择员工-->
        <el-dialog title="选择员工" :visible.sync="dialogEmployeeVisible" width="60%">
            <div>
                <Employee @eventEmployee="eventEmployeeSelectCallBack" />
            </div>
        </el-dialog>

        <el-drawer :title="drawerEditTitle" style="text-align:left;" ref="drawer" :visible.sync="drawerEditVisible"
            :direction="direction">
            <div class="demo-drawer">
                <el-divider content-position="left">登录信息</el-divider>
                <el-form :model="form">
                    <el-form-item label="员工工号" :label-width="formLabelWidth">
                        <el-input placeholder="请选择员工" :disabled="selectEmployeeButton" v-model="form.employeeNo"
                            class="input-with-select">
                            <el-button slot="append" :disabled="selectEmployeeButton" icon="el-icon-search"
                                @click="diaolog_SelectEmployee"></el-button>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="昵称" :label-width="formLabelWidth">
                        <el-input v-model="form.nickName" placeholder="请输入昵称">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" :label-width="formLabelWidth">
                        <el-input type="password" v-model="form.password" :disabled="selectEmployeeButton"
                            placeholder="请输入登录密码，默认为自己工号">
                        </el-input>
                    </el-form-item>
                </el-form>

                <div style="margin-top:50px;">
                    <el-divider content-position="left">角色信息</el-divider>
                    <el-checkbox-group v-model="checkRoleList">
                        <el-checkbox v-for="(item, index) in roleData" :key="index" :label="item.id">
                            {{ item.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
                <div class="demo-drawer-footer">
                    <el-button @click="cancelForm">取 消</el-button>
                    <el-button type="primary" @click="eventEditInfo" :loading="loading">{{
                        loading? '提交中...': '确 定'
                    }}</el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script>
//引入员工列表，作为组件
import Employee from '@/components/employee/List.vue'

export default {
    components: {
        Employee
    },
    data() {
        return {
            input1: '',
            input2: '',
            input3: '',
            select: '',
            multipleSelection: [],
            pages: {
                total: 0,
                pageIndex: 1,
                pageSize: 8
            },
            dataList: []

            //编辑用户相关（drwaer控件）
            ,
            selectEmployeeButton: false,
            drawerEditTitle: '编辑用户信息',
            loading: false,
            drawerEditVisible: false,
            direction: 'rtl',
            form: {
                employeeNo: '',
                nickName: '',
                password: '',
            },
            formLabelWidth: '80px',
            timer: null
            //编辑用户相关（drwaer控件）结束

            //弹出角色相关
            , dialogConfigVisible: false,
            checkRoleList: []
            , roleData: [], //用来初始化角色列表数据
            userId: ''  //用来保存编辑或配置的时候，需要的用户ID
            //弹出角色相关结束

            //弹出员工信息相关
            , dialogEmployeeVisible: false
            //弹出员工信息相关结束
        }
    },
    mounted() {
        this.loadData()
    },
    methods: {
        eventEditInfo() {
            //1、用户的基本信息（用户名、密码、年龄。。。。）
            //2、选中的角色信息（角色ID）
            let data = {
                "user": {
                    "loginName": this.form.employeeNo,
                    "password": this.form.password,
                    "nickName": this.form.nickName,
                    "statue": "0",
                },
                "userRole": [
                    // {
                    //     //"userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", 前台可以生成guid（叫UUID），后台处理更方便
                    //     "roleId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
                    // }
                ]
            }

            //通过Checkbox Group这个控件组的v-model就可以拿到复选框的值
            this.checkRoleList.forEach(x => {
                data.userRole.push({ "roleId": x })
            })

            //console.log(data)

            let url = this.$baseUrl + 'rbac/user/and'
            this.$http.post(url, data).then(res => {
                console.log(res)
            })

        },
        eventEmployeeSelectCallBack(row) {
            this.form.employeeNo = row.employeeNo
            this.form.password = row.employeeNo
            this.userId = row.id
            this.dialogEmployeeVisible = false
        },
        //弹出选择员工
        diaolog_SelectEmployee() {
            this.dialogEmployeeVisible = true
        },
        //提交配置角色
        eventConfigRoleSubmit() {
            this.dialogConfigVisible = false
            this.method_editRoleInfo()
        },
        //编辑配置角色的方法
        method_editRoleInfo() {
            //提交配置角色：需要获取这个用户的ID 和选中的角色ID         
            let url = this.$baseUrl + 'rbac/user/config'
            let data = []
            this.checkRoleList.forEach(x => {
                data.push(
                    {
                        "userId": this.userId,
                        "roleId": x
                    }
                )
            })

            this.$http.post(url, data).then(res => {
                console.log(res)
            })
        },
        //编辑员工信息（包括配置角色）
        method_editUserInfo() {

        },
        //弹出编辑用户
        dialogEditInfo(row) {
            if (row == null) {
                this.form.employeeNo = ''
                this.drawerEditTitle = '添加用户信息'
                this.selectEmployeeButton = false
                this.checkRoleList = []
            }
            else {
                this.drawerEditTitle = '编辑用户信息'
                this.form.employeeNo = row.loginName
                this.checkRoleList = row.roleItems
                this.selectEmployeeButton = true
            }
            this.drawerEditVisible = true
            this.loadRoleData()
        },
        //弹出配置角色
        dialogConfigRole(id) {
            this.dialogConfigVisible = true
            //需要获取该用户的id
            this.userId = id
            //弹出角色配置对话框时，加载角色列表
            this.loadRoleData()
        },
        //加载角色列表
        loadRoleData() {
            let url = this.$baseUrl + 'rbac/role/query/all'
            this.$http.get(url).then(res => {
                this.roleData = res.data.data
            })
        },
        //删除数据（单删除和批量删除用同一个方法：根据row参数来判断，不传参数的是批量删除）
        eventDelete(row) {
            if (row != null) {
                this.multipleSelection.push(row)
            }

            if (this.multipleSelection.length <= 0) {
                this.$message.error('请选择需要删除的数据！')
                return
            }

            this.$confirm('此操作将永久删除被中的数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let url = this.$baseUrl + 'rbac/user/delete'
                this.$http.delete(url, { data: this.multipleSelection }).then(res => {
                    if (res.data.code == 200) {

                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });

                        this.loadData()
                    }
                })
                    .catch(error => {
                        //console.log(error)
                        if (error.code == 'ERR_BAD_REQUEST') {
                            this.$message.error(error.message)
                        }
                    })
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });
            });
        },
        //加载数据列表
        loadData() {
            //let token = localStorage.getItem('token')
            let url = 'http://localhost:5218/rbac/user/query/pages/dynamic'  //?pageIndex=1&pageSize=9'
            this.$http.get(url, {
                params: {
                    pageIndex: this.pages.pageIndex,
                    pageSize: this.pages.pageSize
                }
            }).then(res => {
                this.dataList = res.data.data.items
                this.pages.total = res.data.data.total
            })
        },
        //列表表格选择事件
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //列表分页事件
        handleSizeChange(val) {
            this.pages.pageSize = val
            this.loadData()
        },
        //列表分页事件
        handleCurrentChange(val) {
            this.pages.pageIndex = val
            this.loadData()
        }

        //drawer相关
        ,
        cancelForm() {
            this.loading = false;
            this.drawerEditVisible = false;
            clearTimeout(this.timer);
        },
        handleClose(done) {
            if (this.loading) {
                return;
            }
            this.$confirm('确定要提交表单吗？')
                .then(_ => {
                    this.loading = true;
                    this.timer = setTimeout(() => {
                        //this.userId需要获取选择的员工信息
                        done()
                        // 动画关闭需要一定的时间
                        setTimeout(() => {
                            this.loading = false;
                        }, 400);
                    }, 2000);
                })
                .catch(_ => { });
        },
    }
}
</script>

<style>
.el-select .el-input {
    width: 100px;
}

.input-with-select .el-input-group__prepend {
    background-color: #fff;
}

.demo-drawer {
    position: relative;
    padding: 0 20px;
    height: calc(100% - 30px);
}

.demo-drawer-footer {
    position: absolute;
    bottom: 20px;
}

.el-divider__text {
    font-size: 16px;
    font-weight: 600;
}
</style>